#include "export.h"
#include "fuel_cell_infos.h"
#include "types.h"
#include "main_matrix.h"
//~ #include "mpi_tools.h"
#include "opencl_tools.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

tExport *data = NULL;
int exportSize;

void ExportInit(){
    exportSize = matrixSize.x * matrixSize.y * matrixSize.z * sizeof(tExport);
    messagecl("Export: Init: file size will be %d", exportSize);
    data = secure_malloc_cl(exportSize);

    memset(data, 0, exportSize);
    BuildInfoFile();
}

void ExportFreeMem(){
    if( data != NULL )
        free(data);
}

void BuildInfoFile(){
	FILE *fp;
	fp = fopen("result/info.txt", "w");
	fprintf(fp, "sizex=%d\n", matrixSize.x);
	fprintf(fp, "sizey=%d\n", matrixSize.y);
	fprintf(fp, "sizez=%d\n", matrixSize.z);
	fclose(fp);
}

double ExportIt(int it){
    int i = 0;
    char buffer[512];
    double difference = 0;

    for(int z=0; z<matrixSize.z; z++)
        for(int y=0; y<matrixSize.y; y++)
            for(int x=0; x<matrixSize.x; x++){
                double value = currentMatrix[x][y][z];
                if( ! ( value > 5 && value < 5000) ){
                    die_cl("Unstable, value: %e, coords (%d, %d, %d)", value, x, y, z);
                }
                difference += fabs(data[i] - value);
                data[i++] = currentMatrix[x][y][z];
            }

    sprintf(buffer, "result/it-%010d.dat", it);
    SaveData(buffer, data, exportSize);

    return difference;
}

void SaveData(char *filename, void *data, int size){
    FILE *fp;
    int written;

    fp = fopen(filename, "wb");
    written = fwrite(data, 1, size, fp);

    if(written != size)
        messagecl("ERROR in SaveData : only %d written on %d", written, size);

    fclose(fp);
}
